package com.itheima.stock.service.Impl;

import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockMarketLogPrice;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockMarketLogPriceMapper;
import com.itheima.stock.properties.MarketIndexProperties;
import com.itheima.stock.service.StockServise;
import com.itheima.stock.util.DateTimeUtil;
import com.itheima.stock.vo.InnerMarketVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class StockServiseImpl implements StockServise {

    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private StockMarketIndexInfoMapper smiiMapper;

    @Autowired
    private StockMarketLogPriceMapper smlpMapper;

    @Autowired
    private MarketIndexProperties marketIndexProperties;


    @Override
    public List<StockBusiness> queryStockBusiness() {
        return stockBusinessMapper.selectAll();
    }

    @Override
    public List<InnerMarketVO> innerIndexAll() {
        // 获取大盘编码
        List<String> ids = marketIndexProperties.getInner();

        //获取离现在时间最近的股票交易时间，
        LocalDateTime last = DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());
        //todo mock data 模拟数据
        String nowData = "20211226105600";
        last = LocalDateTime.parse(nowData, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 查询大盘信息
        List<StockMarketIndexInfo> stockMarketIndexInfoList = smiiMapper.selectByIdsAndTime(ids, last);

        //
        List<StockMarketLogPrice> stockMarketLogPriceList = smlpMapper.selectByIdsAndTime(ids, last.toLocalDate());
        return  stockMarketIndexInfoList.stream().map((info)->{
            InnerMarketVO vo = InnerMarketVO.builder().build();
            vo.setCode(info.getMarkId());
            vo.setName(info.getMarkName());
            vo.setCurDate(info.getCurTime().toLocalDate().toString());
            vo.setPreClosePrice(info.getCurrentPrice());
            vo.setUpDown(info.getUpdownRate());
            vo.setTradeAmt(info.getTradeVolume());
            vo.setTradePrice(info.getCurrentPrice());
            stockMarketLogPriceList.forEach(logPrice->{
                if(logPrice.getMarketCode().equals(info.getMarkId())){
                    vo.setOpenPrice(logPrice.getPreClosePrice());
                    vo.setPreClosePrice(logPrice.getOpenPrice());
                }else {
                    vo.setOpenPrice(BigDecimal.ZERO);
                    vo.setPreClosePrice(BigDecimal.ZERO);
                }
            });
            return vo;

        }).toList();
    }


}
